package ink.lovejinhu.leetcode;

import ink.lovejinhu.common.ListNode;
import ink.lovejinhu.common.ProductList;

/**
 * @author jinhu
 * created 2021-07-13 16:59
 */
public class Solution_0019 {
    /**
     * 删除链表倒数第n个节点
     *
     * @param head
     * @param n
     * @return
     */
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode reverse = this.reverse(head);
        if (n == 1) return this.reverse(reverse.next);
        ListNode temp = reverse;
        ListNode pre = null;
        n = n - 1;
        while (n > 0) {
            pre = temp;
            temp = temp.next;
            n--;
        }
        pre.next = temp.next;
        return this.reverse(reverse);
    }


    public ListNode reverse(ListNode head) {

        ListNode newHead = null;
        ListNode change = null;
        while (head != null) {
            change = head.next;
            head.next = newHead;
            newHead = head;
            head =change;

        }
        return newHead;
    }

    public static void main(String[] args) {
        Solution_0019 solution_0019 = new Solution_0019();
        ProductList productList = new ProductList();
        ListNode listNode = productList.creatListByLength(new int[]{1, 2, 3, 4, 5});
        productList.printListNode(listNode);
        // ListNode listNode1 = solution_0019.removeNthFromEnd(listNode, 2);
        //   productList.printListNode(listNode1);
    }
}
